import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Input, Layout, Menu, Spin } from 'antd';
import axios from 'axios';
import { useEffect, useState } from 'react';
import ContentMarket from './ContentMarket';
import './DataMarket.scss';

const { Search } = Input;
const { Footer } = Layout;

const categories = [
  '全部', '目标检测', '文本生成', '图像分类', '对话生成',
  '关系抽取', '机器翻译', '视觉问答', '其他数据集'
];

interface Dataset {
  datasetId: string;
  title: string;
  description: string;
  date: string;
  views: string;
  likes: string;
  comments: number;
  downloads: string;
  shares: string;
  username: string;
  favorites: string;
  tags: string[];
  image: string;
  link: string;
}

const DataMarket = () => {
  const [data, setData] = useState<Dataset[]>([]);
  const [selectedCategory, setSelectedCategory] = useState(categories[0]);
  const [keywords, setKeywords] = useState('');
  const [loading, setLoading] = useState(false);
  const [sortOption, setSortOption] = useState('download_num');
  const [stats, setStats] = useState(''); 
  const [page, setPage] = useState(1);
  const [hasMoreData, setHasMoreData] = useState(true);
  const [lastFetchParams, setLastFetchParams] = useState({
    category: '',
    keywords: '',
    sortOption: ''
  });

  const getRandomDefaultImage = () => {
    const defaultImages = ['/8.png', '/9.png', '/10.png', '/11.jpg', '/12.png'];
    const randomIndex = Math.floor(Math.random() * defaultImages.length);
    return defaultImages[randomIndex];
  };

  const fetchData = async (category: string, keywords: string, sortBy: string, page: number) => {
    console.log('Fetching data:', { category, keywords, sortBy, page });
    if (!hasMoreData || loading) return;

    setLoading(true);
    try {
      const sortByField = sortBy;
      let response;
      
      if (category === '全部') {
        response = await axios.get('http://127.0.0.1:8082/searchDatasets', {
          params: {
            tag: undefined,
            keywords: keywords || undefined,
            sortBy: sortByField,
            page: page
          }
        });
      } else {
        response = await axios.get('http://127.0.0.1:8082/searchDatasets', {
          params: {
            tag: category,
            keywords: keywords || undefined,
            sortBy: sortByField,
            page: page
          }
        });
      }

      const newData = response.data.records.map((record) => ({
        datasetId: record.datasetId,
        title: record.name,
        description: record.description,
        date: record.createdTime,
        views: record.clickNum ? record.clickNum.toString() : '0',
        likes: record.favoriteNum ? record.favoriteNum.toString() : '0',
        comments: 0,
        downloads: record.downloadNum ? record.downloadNum.toString() : '0',
        shares: record.shareNum ? record.shareNum.toString() : '0',
        username: record.creatorName,
        favorites: record.favoriteNum ? record.favoriteNum.toString() : '0',
        tags: record.tags || [],
        image: record.imagePath || getRandomDefaultImage(),
        link: record.url,
      }));

      console.log('Fetched data:', newData);

      // 判断是否还有更多数据
      if (newData.length === 0) {
        setHasMoreData(false);
      } else {
        // 如果 category, keywords, sortOption 任意一个发生变化，则清空旧数据
        if (
          lastFetchParams.category !== category ||
          lastFetchParams.keywords !== keywords ||
          lastFetchParams.sortOption !== sortBy
        ) {
          setData(newData);
          console.log('New params detected, set new data:', newData);
        } else {
          // 否则在旧数据后追加新数据
          setData(prevData => {
            const updatedData = [...prevData, ...newData];
            console.log('Appending data:', updatedData);
            return updatedData;
          });
        }
        setLastFetchParams({ category, keywords, sortOption: sortBy });
        setPage(page + 1); // 自动增加页码
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      setHasMoreData(false); // 防止无限加载
    } finally {
      setLoading(false);
    }
  };

  const fetchStatistics = async () => {
    try {
      const response = await axios.get('http://127.0.0.1:8082/getDatasetStatistics');
      setStats(response.data.msg); 
      console.log('Fetched statistics:', response.data.msg);
    } catch (error) {
      console.error('Error fetching statistics:', error);
    }
  };

  const handleCategoryClick = (category: string) => {
    console.log('Category clicked:', category);
    setSelectedCategory(category);
    setPage(1);
    setHasMoreData(true);
    fetchData(category, keywords, sortOption, 1);
  };

  const handleSearch = (value: string) => {
    console.log('Search initiated:', value);
    setKeywords(value);
    setPage(1);
    setHasMoreData(true);
    fetchData(selectedCategory, value, sortOption, 1);
  };

  const handleSortChange = (key: string) => {
    console.log('Sort option changed:', key);
    setSortOption(key);
    setPage(1);
    setHasMoreData(true);
    fetchData(selectedCategory, keywords, key, 1);
  };
  
  const sortMenu = (
    <Menu onClick={(e) => handleSortChange(e.key)}>
      <Menu.Item key="download_num">最热</Menu.Item>
      <Menu.Item key="created_time">最新</Menu.Item>
    </Menu>
  );

  const menu = (
    <Menu>
      {categories.slice(8).map((category, index) => (
        <Menu.Item key={index} onClick={() => handleCategoryClick(category)}>
          {category}
        </Menu.Item>
      ))}
    </Menu>
  );

  useEffect(() => {
    console.log('Effect triggered: sortOption or page changed');
    fetchData(selectedCategory, keywords, sortOption, page);
  }, [sortOption, page]);

  useEffect(() => {
    console.log('Effect triggered: fetch statistics');
    fetchStatistics(); 
  }, []);

  return (
    <div className="data-market">
      <div className='top-menu'>
        <h1>数据广场</h1>
        <div className="search-bar">
          <Dropdown overlay={sortMenu}>
            <Button className="sort-button" style={{ border: 'none', backgroundColor: 'transparent' }}>
              排序：{sortOption === 'download_num' ? '最热' : '最新'} <DownOutlined />
            </Button>
          </Dropdown>
          <p style={{ margin: '0 1.25rem' }}>筛选：{selectedCategory} ▼</p>
          <Search
            placeholder="搜索数据集"
            style={{ width: 240 }}
            onSearch={handleSearch}
          />
          <Button type="primary" className='start-chat-button'>创建数据集</Button>
        </div>
      </div>
      <div className="category-menu">
        {categories.slice(0, 10).map((category, index) => (
          <Button
            key={index}
            type={selectedCategory === category ? 'primary' : 'default'}
            style={{ borderColor: 'white', borderRadius: '0rem' }}
            onClick={() => handleCategoryClick(category)}
          >
            {category}
          </Button>
        ))}
        <Dropdown overlay={menu}>
          <Button style={{ borderColor: 'white', borderRadius: '0rem' }}>
            更多 <DownOutlined />
          </Button>
        </Dropdown>
        <div className="statistics">
          <p>{stats}</p> {/* 显示统计信息 */}
        </div>
      </div>
      
      <div className="data-content">
        <Footer className="scrollable-footer">
          {data.length > 0 && (
            <div className="scrollable-content" style={{ maxHeight: '1000px', overflowY: 'auto' }}>
              <ContentMarket apps={data} />
            </div>
          )}
          {loading && (
            <div style={{ textAlign: 'center', marginTop: '20px' }}>
              <Spin size="large" />
            </div>
          )}
        </Footer>
      </div>
    </div>
  );
};

export default DataMarket;